直接來上今天的題目:
/*
We have an array A of integers, and an array queries of queries.
For the i-th query val = queries[i][0], index = queries[i][1], we add val to A[index]. Then, the answer to the i-th query is the sum of the even values of A.
(Here, the given index = queries[i][1] is a 0-based index, and each query permanently modifies the array A.)
Return the answer to all queries. Your answer array should have answer[i] as the answer to the i-th query.
Example 1:
Input: A = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]
Output: [8,6,2,4]
Explanation:
At the beginning, the array is [1,2,3,4].
After adding 1 to A[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.
After adding -3 to A[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.
After adding -4 to A[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.
After adding 2 to A[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4.
*/
var sumEvenAfterQueries = function(A, queries) {
};
今天這題的題目給的相當詳細,傳入兩個陣列,一個是單純數字陣列,另一個是包含了值與索引所組合的陣列。最後輸出每一次修改後偶數的總和的陣列。
思考:
var sumEvenAfterQueries = function(A, queries) {
let result = []
return result
};
var sumEvenAfterQueries = function(A, queries) {
let result = []
queries.forEach((query)=>{
})
return result
};
var sumEvenAfterQueries = function(A, queries) {
let result = []
let evenA
queries.forEach((query)=>{
A[query[1]] += query[0]
evenA = A.filter((num)=> num % 2 === 0)
result.push(evenA.reduce((sum, num)=>{return sum + num}))
})
return result
};
var sumEvenAfterQueries = function(A, queries) {
let result = []
let evenA
queries.forEach((query)=>{
A[query[1]] += query[0]
evenA = A.filter((num)=> num % 2 === 0)
if (evenA.length === 0){
evenA[0] = 0
}
result.push(evenA.reduce((sum, num)=>{return sum + num}))
})
return result
};
以上是今天的內容,寫法上有非常大的進步空間。如果有哪位大大路過經過,還請多多指教。